const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 获取所有成就定义
 */
const getAllAchievements = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [achievements] = await db.execute(
            `SELECT 
                a.*,
                CASE WHEN ua.id IS NOT NULL THEN 1 ELSE 0 END as unlocked,
                ua.unlocked_at,
                0 as current,
                a.target
             FROM achievements a
             LEFT JOIN user_achievements ua ON a.id = ua.achievement_id AND ua.user_id = ?
             WHERE a.enabled = 1
             ORDER BY a.id`,
            [userId]
        );
        
        // 计算每个成就的进度
        const achievementsWithProgress = achievements.map(a => ({
            ...a,
            progress: a.target > 0 ? Math.min((a.current / a.target) * 100, 100) : 0
        }));
        
        return successResponse(res, achievementsWithProgress);
        
    } catch (error) {
        console.error('获取成就列表错误:', error);
        return errorResponse(res, '获取成就列表失败', 500, error);
    }
};

/**
 * 获取用户已解锁的成就
 */
const getUserAchievements = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [achievements] = await db.execute(
            `SELECT 
                a.*,
                CASE WHEN ua.id IS NOT NULL THEN 1 ELSE 0 END as unlocked,
                ua.unlocked_at,
                0 as current,
                a.target
             FROM achievements a
             LEFT JOIN user_achievements ua ON a.id = ua.achievement_id AND ua.user_id = ?
             WHERE a.enabled = 1
             ORDER BY a.id`,
            [userId]
        );
        
        // 添加进度计算
        const achievementsWithProgress = achievements.map(a => ({
            ...a,
            progress: a.target > 0 ? Math.min((a.current / a.target) * 100, 100) : 0
        }));
        
        return successResponse(res, achievementsWithProgress);
        
    } catch (error) {
        console.error('获取用户成就错误:', error);
        return errorResponse(res, '获取用户成就失败', 500, error);
    }
};

/**
 * 检查并解锁成就
 */
const checkAndUnlockAchievements = async (req, res) => {
    const connection = await db.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const userId = req.user.id;
        const newAchievements = [];
        
        // 获取用户统计数据
        const [userStats] = await connection.execute(
            `SELECT 
                u.*,
                COUNT(DISTINCT up.word_id) as words_learned,
                COUNT(DISTINCT ua.achievement_id) as achievements_count,
                COUNT(DISTINCT f.friend_id) as friends_count,
                COUNT(DISTINCT gr.id) as games_played
             FROM users u
             LEFT JOIN user_progress up ON u.id = up.user_id
             LEFT JOIN user_achievements ua ON u.id = ua.user_id
             LEFT JOIN friendships f ON (u.id = f.user_id OR u.id = f.friend_id) AND f.status = 'accepted'
             LEFT JOIN game_records gr ON u.id = gr.user_id
             WHERE u.id = ?
             GROUP BY u.id`,
            [userId]
        );
        
        if (userStats.length === 0) {
            await connection.rollback();
            return errorResponse(res, '用户不存在', 404);
        }
        
        const stats = userStats[0];
        
        // 获取所有成就定义
        const [allAchievements] = await connection.execute(
            'SELECT * FROM achievement_definitions'
        );
        
        // 检查每个成就
        for (const achievement of allAchievements) {
            // 检查是否已解锁
            const [existing] = await connection.execute(
                'SELECT id FROM user_achievements WHERE user_id = ? AND achievement_id = ?',
                [userId, achievement.id]
            );
            
            if (existing.length > 0) continue;
            
            let shouldUnlock = false;
            
            // 根据不同类型检查是否满足条件
            switch (achievement.requirement_type) {
                case 'words_learned':
                    shouldUnlock = stats.words_learned >= achievement.requirement_value;
                    break;
                case 'continuous_days':
                    shouldUnlock = stats.continuous_days >= achievement.requirement_value;
                    break;
                case 'games_played':
                    shouldUnlock = stats.games_played >= achievement.requirement_value;
                    break;
                case 'friends_count':
                    shouldUnlock = stats.friends_count >= achievement.requirement_value;
                    break;
                case 'correct_streak':
                    // 这个需要单独查询连续答对记录（简化处理，暂不实现）
                    break;
            }
            
            // 解锁成就
            if (shouldUnlock) {
                await connection.execute(
                    'INSERT INTO user_achievements (user_id, achievement_id) VALUES (?, ?)',
                    [userId, achievement.id]
                );
                
                // 奖励星星
                if (achievement.stars_reward > 0) {
                    await connection.execute(
                        'UPDATE users SET stars = stars + ? WHERE id = ?',
                        [achievement.stars_reward, userId]
                    );
                }
                
                newAchievements.push({
                    ...achievement,
                    unlocked_at: new Date()
                });
            }
        }
        
        await connection.commit();
        
        return successResponse(res, {
            newAchievements,
            count: newAchievements.length
        }, newAchievements.length > 0 ? `恭喜！解锁了 ${newAchievements.length} 个成就` : '暂无新成就');
        
    } catch (error) {
        await connection.rollback();
        console.error('检查成就错误:', error);
        return errorResponse(res, '检查成就失败', 500, error);
    } finally {
        connection.release();
    }
};

/**
 * 获取成就进度
 */
const getAchievementProgress = async (req, res) => {
    try {
        const userId = req.user.id;
        
        // 获取用户统计数据
        const [userStats] = await db.execute(
            `SELECT 
                u.*,
                COUNT(DISTINCT up.word_id) as words_learned,
                COUNT(DISTINCT f.friend_id) as friends_count,
                COUNT(DISTINCT gr.id) as games_played
             FROM users u
             LEFT JOIN user_progress up ON u.id = up.user_id
             LEFT JOIN friendships f ON (u.id = f.user_id OR u.id = f.friend_id) AND f.status = 'accepted'
             LEFT JOIN game_records gr ON u.id = gr.user_id
             WHERE u.id = ?
             GROUP BY u.id`,
            [userId]
        );
        
        const stats = userStats[0];
        
        // 构建进度对象
        const progress = {
            words_learned: stats.words_learned,
            continuous_days: stats.continuous_days,
            games_played: stats.games_played,
            friends_count: stats.friends_count
        };
        
        return successResponse(res, progress);
        
    } catch (error) {
        console.error('获取成就进度错误:', error);
        return errorResponse(res, '获取成就进度失败', 500, error);
    }
};

module.exports = {
    getAllAchievements,
    getUserAchievements,
    checkAndUnlockAchievements,
    getAchievementProgress
};

